package edu.cmu.cs.task7.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ebay.sdk.ApiContext;
import com.ebay.sdk.ApiException;
import com.ebay.sdk.SdkException;
import com.ebay.sdk.helper.ServiceControlManager;
import com.ebay.sdk.helper.ShippingServiceHelper;
import com.ebay.sdk.helper.ui.ControlTagItem;
import com.ebay.soap.eBLBaseComponents.ItemType;
import com.ebay.soap.eBLBaseComponents.ListingStatusCodeType;
import com.ebay.soap.eBLBaseComponents.SellingStatusType;
import com.ebay.soap.eBLBaseComponents.SiteCodeType;
import com.ebay.sdk.ApiCall;

import edu.cmu.cs.task7.databeans.ProductStat;
import edu.cmu.cs.task7.model.AddItemModel;
import edu.cmu.cs.task7.model.EndItemModel;
import edu.cmu.cs.task7.model.GetAllItemsModel;
import edu.cmu.cs.task7.model.GetItemModel;
import edu.cmu.cs.task7.model.Model;
import edu.cmu.cs.task7.model.RelistItemModel;
import edu.cmu.cs.task7.model.PriceResearchModel;
import edu.cmu.cs.task7.model.ReviseItemModel;

import com.oreilly.servlet.MultipartRequest;


/**
 * Servlet implementation class Controller
 */
@WebServlet("/Controller")
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private ApiContext apiContext=new ApiContext();    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Controller() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init() throws ServletException {
        Model m;
		try {
			m = new Model();
			this.apiContext=m.apiContext;
		} catch (Exception e) {
			e.printStackTrace();
		}  
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String      servletPath = request.getServletPath();
		int slash = servletPath.lastIndexOf('/');
        String action= servletPath.substring(slash+1);
        
        //First check whether the user is already logged in    
        HttpSession session = request.getSession(); 
        
        
        //Then check whether the user tries to login or logout
        if(action.equals("login.do")){
        	 if(request.getParameter("username").equals("testuser_cmuteam4")&&
        			 request.getParameter("password").equals("CMU_team4")){
	       	     session.setAttribute("user","testuser_cmuteam4");
	       	     try {
					outputAddItem(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
        	 }else{
        		 login(request,response);
        	 }
        }else if (session.getAttribute("user") == null) {
       	   login(request,response);
        }else if(action.equals("logout.do")){
    		 session.invalidate();
    		 login(request,response);
        }  
        
        
        //Then output the input forms of all functions
        RequestDispatcher d;
        if(action.equals("AllItems.do")){
        	try {
				outputAllItems(request,response);
			} catch (Exception e) {
				e.printStackTrace();
			} 	
        }else if(action.equals("AddItem-1.do")){
        	try {
				outputAddItem(request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else if(action.equals("GetItem-1.do")){
        	try {
        		d = request.getRequestDispatcher("GetItem.jsp");
                d.forward(request,response);
                return;
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else if(action.equals("EndItem-1.do")){
        	try {
        		d = request.getRequestDispatcher("EndItem.jsp");
                d.forward(request,response);
                return;
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else if(action.equals("PriceResearch-1.do")){
        	try {
        		d = request.getRequestDispatcher("PriceResearch.jsp");
                d.forward(request,response);
                return;
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else if(action.equals("RelistItem-1.do")){
        	try {
        		d = request.getRequestDispatcher("RelistItem-1.jsp");
                d.forward(request,response);
                return;
			} catch (Exception e) {
				e.printStackTrace();
			}
        }else if(action.equals("ReviseItem-1.do")){
        	try {
        		d = request.getRequestDispatcher("ReviseItem-1.jsp");
                d.forward(request,response);
                return;
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        
        
        
        
        //Then comes the second/third phase of all items
		if(action.equals("GetItem-2.do")){
			String itemid=request.getParameter("itemid");
			try {
               outputItemDetail(itemid,request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(action.equals("EndItem-2.do")){
			String itemid_end=request.getParameter("itemid_end");
			String endreason=request.getParameter("endreason");
			try {
				outputEndItemResult(itemid_end,endreason,request,response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(action.equals("ReviseItem-2.do")){
			String itemid=request.getParameter("itemid");
			try {
               outputReviseItem(itemid,request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(action.equals("ReviseItem-3.do")){
			try {
               outputReviseItemResult(request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(action.equals("RelistItem-2.do")){
			String itemid=request.getParameter("itemid");
			try {
               outputRelistItem(itemid,request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(action.equals("RelistItem-3.do")){
			try {
               outputRelistItemResult(request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(action.equals("PriceResearch-2.do")){
			String product=request.getParameter("product");
			try {
				outputProductStat(product,request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		else if(action.equals("AddItem-2.do")){ //For adding an item
			try {
				outputAddItemResult(request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		else{
        	try {
				outputAddItem(request,response);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		 RequestDispatcher d = request.getRequestDispatcher("login.jsp");
	     d.forward(request,response);
	     return; 
	}
	
	
//	protected void outputHomePage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ 
//	    ServiceControlManager manager = ServiceControlManager.getInstance();
//	    ControlTagItem[] ctrlServices = manager.createShippingServiceControl(SiteCodeType.US, ShippingServiceHelper.FLAT_SHIPPING_METHODS, false);
//	    request.setAttribute("ctrlServices",ctrlServices);
//        RequestDispatcher d = request.getRequestDispatcher("Homepage.jsp");
//        d.forward(request,response);
//        return; 
//	}
	
	
	protected void outputAllItems(HttpServletRequest request, HttpServletResponse response) throws ApiException, SdkException, Exception{ 
		GetAllItemsModel gt=new GetAllItemsModel(this.apiContext);
	    HashMap itemsHM=gt.getAllItems();
	    final ItemType[] unSoldItems = (ItemType[]) itemsHM.get("unsold");
	    String[] ui=new String[unSoldItems.length];
	    for(int i=0;i<ui.length;i++){
	    	ui[i]=unSoldItems[i].getItemID();
	    }
	    String[] uititles=new String[unSoldItems.length];
	    for(int i=0;i<uititles.length;i++){
	    	uititles[i]=unSoldItems[i].getTitle();
	    }
	    final ItemType[] activeItems = (ItemType[]) itemsHM.get("active");
	    String[] ai=new String[activeItems.length];
	    for(int i=0;i<ai.length;i++){
	    	ai[i]=activeItems[i].getItemID();
	    }
	    String[] aititles=new String[activeItems.length];
	    for(int i=0;i<aititles.length;i++){
	    	aititles[i]=activeItems[i].getTitle();
	    }
	    request.setAttribute("ui", ui);
	    request.setAttribute("ai", ai);
	    request.setAttribute("uititles", ui);
	    request.setAttribute("aititles", ai);
        RequestDispatcher d = request.getRequestDispatcher("GetAllItems.jsp");
        d.forward(request,response);
        return;
	
	}
	
	
	
    protected void outputItemDetail(String itemid,HttpServletRequest request, HttpServletResponse response) throws Exception{
		GetItemModel gt=new GetItemModel(this.apiContext,itemid);
		ItemType item=gt.getItem();
        
		SellingStatusType sst= item.getSellingStatus();
		ListingStatusCodeType lst=sst.getListingStatus();
		String status=lst.value();
		
		
		request.setAttribute("itemstatus",status);
	    request.setAttribute("itemid",item.getItemID());
	    request.setAttribute("title",item.getTitle());
	    request.setAttribute("quantity",item.getQuantity().toString());
	    request.setAttribute("currentprice",new Double(item.getSellingStatus().getCurrentPrice().getValue()).toString());
	    request.setAttribute("description",item.getDescription());
	    request.setAttribute("startprice", item.getStartPrice().getValue());
	    request.setAttribute("reserveprice", item.getReservePrice().getValue()); 
	    request.setAttribute("binprice", item.getBuyItNowPrice().getValue());
	    request.setAttribute("duration", item.getListingDuration());
	    request.setAttribute("picpath", item.getPictureDetails().getPictureURL(0));
        RequestDispatcher d = request.getRequestDispatcher("GetItemDetail.jsp");
        d.forward(request,response);
        return;
	}
	
	
	protected void outputEndItemResult(String itemid_end,String endreason,HttpServletRequest request,HttpServletResponse response) throws Exception{
	    EndItemModel et=new EndItemModel(this.apiContext,itemid_end,endreason);
		String end_time=et.endItem();
		request.setAttribute("end_time",end_time);
		RequestDispatcher d = request.getRequestDispatcher("EndItemResult.jsp");
        d.forward(request,response);
        return;
	}
	
	
	protected void outputReviseItem(String itemid,HttpServletRequest request,HttpServletResponse response) throws Exception{
		GetItemModel gt=new GetItemModel(this.apiContext,itemid);
		ItemType item=gt.getItem();
        
		SellingStatusType sst= item.getSellingStatus();
		ListingStatusCodeType lst=sst.getListingStatus();
		String status=lst.value();
		if(status.equals("Completed")){
			try {
				request.setAttribute("errormsg", "You cannot revise ended item");
				RequestDispatcher ds = request.getRequestDispatcher("ReviseItem-1.jsp");
                ds.forward(request,response);
                return;
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		request.setAttribute("itemid",itemid);
		request.setAttribute("title",item.getTitle());
	    request.setAttribute("quantity",item.getQuantity().toString());
	    request.setAttribute("description",item.getDescription());
	    request.setAttribute("startprice", item.getStartPrice().getValue());
	    request.setAttribute("reserveprice", item.getReservePrice().getValue()); 
	    request.setAttribute("binprice", item.getBuyItNowPrice().getValue());
	    //request.setAttribute("duration", item.getListingDuration());
        RequestDispatcher d = request.getRequestDispatcher("ReviseItem-2.jsp");
        d.forward(request,response);
        return;
	}
	
	protected void outputReviseItemResult(HttpServletRequest request,HttpServletResponse response){
		HashMap params=new HashMap();
		params.put("itemid",request.getParameter("itemid"));
		params.put("title",request.getParameter("item_title"));
		params.put("quantity", request.getParameter("quantity"));
		params.put("startprice", request.getParameter("startprice"));
		params.put("reserveprice", request.getParameter("reserveprice"));
		params.put("binprice", request.getParameter("binprice"));
		params.put("description", request.getParameter("description"));
		ReviseItemModel rm;
		try {
		    rm = new ReviseItemModel(this.apiContext,params);
			String[] results=rm.reviseItem();
			request.setAttribute("results",results);
			RequestDispatcher d = request.getRequestDispatcher("ReviseItem-3.jsp");
	        d.forward(request,response);
	        return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	protected void outputRelistItem(String itemid,HttpServletRequest request,HttpServletResponse response) throws Exception{
		GetItemModel gt=new GetItemModel(this.apiContext,itemid);
		ItemType item=gt.getItem();
        
		
		SellingStatusType sst= item.getSellingStatus();
		ListingStatusCodeType lst=sst.getListingStatus();
		String status=lst.value();
		if(status.equals("Active")){
			try {
				request.setAttribute("errormsg", "You cannot relist active item");
				RequestDispatcher ds = request.getRequestDispatcher("RelistItem-1.jsp");
                ds.forward(request,response);
                return;
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		
		request.setAttribute("itemid",itemid);
		request.setAttribute("title",item.getTitle());
	    request.setAttribute("quantity",item.getQuantity().toString());
	    request.setAttribute("description",item.getDescription());
	    request.setAttribute("startprice", item.getStartPrice().getValue());
	    request.setAttribute("reserveprice", item.getReservePrice().getValue()); 
	    request.setAttribute("binprice", item.getBuyItNowPrice().getValue());
	    //request.setAttribute("duration", item.getListingDuration());
        RequestDispatcher d = request.getRequestDispatcher("RelistItem-2.jsp");
        d.forward(request,response);
        return;
	}
	
	protected void outputRelistItemResult(HttpServletRequest request,HttpServletResponse response){
		HashMap params=new HashMap();
		params.put("itemid",request.getParameter("itemid"));
		params.put("title",request.getParameter("item_title"));
		params.put("quantity", request.getParameter("quantity"));
		params.put("startprice", request.getParameter("startprice"));
		params.put("reserveprice", request.getParameter("reserveprice"));
		params.put("binprice", request.getParameter("binprice"));
		params.put("description", request.getParameter("description"));
		RelistItemModel rm;
		try {
		    rm = new RelistItemModel(this.apiContext,params);
			String[] results=rm.relistItem();
			request.setAttribute("results",results);
			RequestDispatcher d = request.getRequestDispatcher("RelistItem-3.jsp");
	        d.forward(request,response);
	        return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void outputProductStat(String productKeyword,HttpServletRequest request, HttpServletResponse response) throws Exception{
		PriceResearchModel gt=new PriceResearchModel(productKeyword);
		ProductStat ps=gt.getProductStat();
		request.setAttribute("keyword",productKeyword);
		request.setAttribute("totalSales",ps.getTotalSales());
		request.setAttribute("soldItems",ps.getSoldItems());
		request.setAttribute("avgSoldPrice",ps.getAvgSoldPrice());
		request.setAttribute("maxSoldPrice",ps.getMaxSoldPrice());
		request.setAttribute("minSoldPrice",ps.getMinSoldPrice());
		RequestDispatcher d = request.getRequestDispatcher("GetPriceResearchData.jsp");
        d.forward(request,response);
        return;
	}
	
	
	protected void  outputAddItem(HttpServletRequest request,HttpServletResponse response) throws Exception{
		RequestDispatcher d = request.getRequestDispatcher("AddItem.jsp");
        d.forward(request,response);
        return;
	}
	
	
	protected void outputAddItemResult(HttpServletRequest request,HttpServletResponse response) throws Exception{
		MultipartRequest mq = null;
		Boolean isMultipart=false;
		if (request.getContentType() != null && 
			    request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ){
		     mq=new MultipartRequest(request,"C:\\CMPT\\javaproject\\task7\\uploads",8096000);
		     isMultipart=true;
		}
		
		HashMap params=new HashMap();
		params.put("title",mq.getParameter("item_title"));
		params.put("categoryid", mq.getParameter("categoryid"));
		params.put("listingtype", mq.getParameter("listingtype"));
		params.put("quantity", mq.getParameter("quantity"));
		params.put("lotsize", mq.getParameter("lotsize"));
		params.put("duration", mq.getParameter("duration"));
		params.put("startprice", mq.getParameter("startprice"));
		params.put("reserveprice", mq.getParameter("reserveprice"));
		params.put("binprice", mq.getParameter("binprice"));
		params.put("conditionid", mq.getParameter("conditionid"));
		params.put("paypalemail", mq.getParameter("paypalemail"));
		
//		String autopay=mq.getParameter("autopay");  //There is error regarding autopay; 
		                                         //demanding to upgrade paypal, which is no possible in sandbox
//		if(autopay==null){
//		   params.put("autopay",false);
//		}else{
//			params.put("autopay",true);
//		}
		params.put("postalcode", mq.getParameter("postalcode"));
		params.put("vatpercent", mq.getParameter("vatpercent"));
		String boldtitle=mq.getParameter("boldtitle");
		if(boldtitle==null){
		   params.put("boldtitle",false);
		}else{
			params.put("boldtitle",true);
		}
		params.put("description", mq.getParameter("description"));
		params.put("location", mq.getParameter("location"));
		
		File picfile=mq.getFile("picpath");  //Construct a file object from the uploaded file in our server
		if(picfile==null){  //The form is not compeleted, forward back to add item page
			request.setAttribute("errormsg","Some attributes are not complete in this form. Please fill all of them");
			RequestDispatcher d = request.getRequestDispatcher("AddItem.jsp");
	        d.forward(request,response);
	        return;
		}
		String pic=picfile.getAbsolutePath(); //Get the absolute path so that we can pass this to ebay server
		String[] picturepaths=new String[1];
		picturepaths[0]=pic;
		System.out.println(picturepaths[0]);
		params.put("picturepaths",picturepaths);
		String[] ckbpaymethods=mq.getParameterValues("ckbpaymethods");   //Use getParameterValues to get group of values
		params.put("ckbpaymethods", ckbpaymethods);
		String[] ckbShipToLocations=mq.getParameterValues("ckbShipToLocations");
		params.put("ckbShipToLocations", ckbShipToLocations);
		params.put("shippingserviceindex", mq.getParameter("shippingserviceindex"));
		params.put("shippingservicecost", mq.getParameter("shippingservicecost"));
		params.put("additionalshippingservicecost", mq.getParameter("additionalshippingservicecost"));
//		for(int i=0;i<params.size();i++){ //The form is not compeleted, forward back to add item page
//			if(params.get(i)==null||params.get(i).equals("")){
//				request.setAttribute("errormsg","Some attributes are not complete in this form. Please fill all of them");
//				RequestDispatcher d = request.getRequestDispatcher("AddItem.jsp");
//		        d.forward(request,response);
//		        return;
//			}
//		}
		
		
		AddItemModel am;
		try {
			am = new AddItemModel(this.apiContext,params);
			String[] results=am.AddItem();
			if(results[0].equals("error")){ //If there is an error
				request.setAttribute("errormsg",results[1]);
				RequestDispatcher d = request.getRequestDispatcher("AddItem.jsp");
		        d.forward(request,response);
				return;
			}
			request.setAttribute("results",results);
			RequestDispatcher d = request.getRequestDispatcher("AddItemResult.jsp");
	        d.forward(request,response);
	        return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
